<template>
  <a-form
    ref="formRef"
    :model="formData"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    :disabled="disabled"
    v-bind="$attrs"
  >
    <a-row :gutter="16">
      <a-col
        v-for="field in fields"
        :key="field.name"
        :span="field.span || 24"
      >
        <a-form-item
          :label="field.label"
          :name="field.name"
          :rules="field.rules"
        >
          <!-- Input 输入框 -->
          <a-input
            v-if="field.type === 'input'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            v-bind="field.props"
          />

          <!-- Password 密码框 -->
          <a-input-password
            v-else-if="field.type === 'password'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            v-bind="field.props"
          />

          <!-- Email 邮箱输入 -->
          <a-input
            v-else-if="field.type === 'email'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            type="email"
            v-bind="field.props"
          />

          <!-- Number 数字输入 -->
          <a-input-number
            v-else-if="field.type === 'number'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            style="width: 100%"
            v-bind="field.props"
          />

          <!-- Select 下拉选择 -->
          <a-select
            v-else-if="field.type === 'select'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            :options="field.options"
            v-bind="field.props"
          />

          <!-- Date 日期选择 -->
          <a-date-picker
            v-else-if="field.type === 'date'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            style="width: 100%"
            v-bind="field.props"
          />

          <!-- Textarea 多行文本 -->
          <a-textarea
            v-else-if="field.type === 'textarea'"
            v-model:value="formData[field.name]"
            :placeholder="field.placeholder"
            :disabled="field.disabled"
            :rows="4"
            v-bind="field.props"
          />

          <!-- Radio 单选 -->
          <a-radio-group
            v-else-if="field.type === 'radio'"
            v-model:value="formData[field.name]"
            :disabled="field.disabled"
            v-bind="field.props"
          >
            <a-radio
              v-for="option in field.options"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-radio>
          </a-radio-group>

          <!-- Checkbox 多选 -->
          <a-checkbox-group
            v-else-if="field.type === 'checkbox'"
            v-model:value="formData[field.name]"
            :disabled="field.disabled"
            :options="field.options"
            v-bind="field.props"
          />
        </a-form-item>
      </a-col>
    </a-row>

    <!-- 底部按钮区域 -->
    <a-form-item v-if="showFooter" :wrapper-col="footerWrapperCol">
      <slot name="footer">
        <a-space>
          <a-button type="primary" :loading="loading" @click="handleSubmit">
            {{ submitText }}
          </a-button>
          <a-button v-if="showReset" @click="handleReset">
            {{ resetText }}
          </a-button>
          <a-button v-if="showCancel" @click="handleCancel">
            {{ cancelText }}
          </a-button>
        </a-space>
      </slot>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import type { FormInstance } from 'ant-design-vue'
import type { FormFieldConfig } from '@/types'

/**
 * 组件 Props
 */
export interface CommonFormProps {
  fields: FormFieldConfig[]
  initialValues?: Record<string, any>
  labelCol?: { span?: number; style?: any }
  wrapperCol?: { span?: number; style?: any }
  loading?: boolean
  disabled?: boolean
  showFooter?: boolean
  showReset?: boolean
  showCancel?: boolean
  submitText?: string
  resetText?: string
  cancelText?: string
}

const props = withDefaults(defineProps<CommonFormProps>(), {
  fields: () => [],
  labelCol: () => ({ span: 6 }),
  wrapperCol: () => ({ span: 18 }),
  loading: false,
  disabled: false,
  showFooter: true,
  showReset: true,
  showCancel: false,
  submitText: '提交',
  resetText: '重置',
  cancelText: '取消',
})

/**
 * 组件 Emits
 */
const emit = defineEmits<{
  submit: [values: Record<string, any>]
  cancel: []
}>()

/**
 * 表单引用
 */
const formRef = ref<FormInstance>()

/**
 * 表单数据
 */
const formData = reactive<Record<string, any>>({})

/**
 * 初始化表单数据
 */
function initFormData() {
  // 清空现有数据
  Object.keys(formData).forEach((key) => {
    delete formData[key]
  })

  // 设置默认值
  props.fields.forEach((field) => {
    if (field.defaultValue !== undefined) {
      formData[field.name] = field.defaultValue
    }
  })

  // 设置初始值（初始值优先级高于默认值）
  if (props.initialValues) {
    Object.assign(formData, props.initialValues)
  }
}

/**
 * 监听初始值变化
 */
watch(
  () => props.initialValues,
  () => {
    initFormData()
  },
  { immediate: true, deep: true }
)

/**
 * 监听字段配置变化
 */
watch(
  () => props.fields,
  () => {
    initFormData()
  },
  { deep: true }
)

/**
 * 底部按钮区域布局
 */
const footerWrapperCol = computed(() => ({
  span: props.wrapperCol.span,
  offset: props.labelCol.span,
}))

/**
 * 提交表单
 */
async function handleSubmit() {
  try {
    await formRef.value?.validate()
    emit('submit', { ...formData })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

/**
 * 重置表单
 */
function handleReset() {
  formRef.value?.resetFields()
  initFormData()
}

/**
 * 取消操作
 */
function handleCancel() {
  emit('cancel')
}

/**
 * 验证表单
 */
async function validate(): Promise<Record<string, any>> {
  await formRef.value?.validate()
  return { ...formData }
}

/**
 * 重置字段
 */
function resetFields() {
  formRef.value?.resetFields()
}

/**
 * 设置字段值
 */
function setFieldsValue(values: Record<string, any>) {
  Object.assign(formData, values)
}

/**
 * 获取字段值
 */
function getFieldsValue(): Record<string, any> {
  return { ...formData }
}

/**
 * 清空字段验证
 */
function clearValidate(names?: string[]) {
  formRef.value?.clearValidate(names)
}

/**
 * 暴露方法给父组件
 */
defineExpose({
  validate,
  resetFields,
  setFieldsValue,
  getFieldsValue,
  clearValidate,
})
</script>

<style scoped lang="less">
// 可以在这里添加自定义样式
</style>
